#pragma once
#include "Com.hpp"
#include "Socket.hpp"
#include "Protocol.hpp"
#include "Log.hpp"
#include <functional>
#include <memory>
#include <sys/types.h>
#include <sys/wait.h>
using server_func_t = std::function<void(std::shared_ptr<Socket> sock , InetAddr client)>;

class TcpServer
{
    public:
    TcpServer(uint16_t port,server_func_t func)
        :_func(func)
        ,_port(port)
        ,_listensockptr(std::make_unique<TcpSocket>())
        ,_isrunning(false)
    {
        _listensockptr->BuildTcpSocketMethod(port , 8);
    }
    ~TcpServer()
    {

    }
    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            InetAddr client;
            auto sock = _listensockptr->Accept(&client); 
            if(sock == nullptr)
            {
                continue;
            }
            pid_t pid = fork();
            if(pid > 0)
            {
                //子进程
                if(fork() == 0)
                {
                    exit(OK);
                }
                //孙子进程
                _listensockptr->Close();
                _func(sock , client);
                sock->Close();
                exit(OK);
            }
            //父进程
            waitpid(pid , nullptr ,0);
            sock->Close();
        }
        _isrunning = false;
    }
    private:
    server_func_t _func;
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr;
    bool _isrunning;
};